package net.kts.placebook.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import net.kts.placebook.gallery.Photo;
import net.kts.placebook.session.FoursquareSession;
import net.kts.placebook.tips.Tips;
import net.kts.placebook.venue.Venue;
import net.kts.transrate.TranslateService;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

public class PlacebookDao {
	
	private static final String FS_API_URL = "https://api.foursquare.com/v2";
	
	public static final String tagName = "fs333";

	private FoursquareSession fs;
	
	public PlacebookDao(Activity activity){
		fs = new FoursquareSession(activity);
	}
	
	// 가까운 장소 리스트 가져오기
	public ArrayList<Venue> getNearby(double latitude, double longitude) throws Exception {
		
		Log.i(tagName, "getNearby 실행 lat, long" + latitude + " : " + longitude);
		
		ArrayList<Venue> venueList = new ArrayList<Venue>();

		try {
			String ll 	= String.valueOf(latitude) + "," + String.valueOf(longitude);
			URL url 	= new URL(FS_API_URL + "/venues/search?ll=" + ll + "&limit=15" + "&oauth_token=" + fs.getAccessToken());

			Log.i(tagName, "유알엘 열기 : " + url.toString());

			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);

			urlConnection.connect();

			String response		= streamToString(urlConnection.getInputStream());
			JSONObject jsonObj 	= (JSONObject) new JSONTokener(response).nextValue();

			JSONArray groups	= jsonObj.getJSONObject("response").getJSONArray("groups");

			int length			= groups.length();
			
			Log.i(tagName, "Groups 길이 : " + length);
			
			if (length > 0) {
				Log.i(tagName, "가까운 위치 목록 1 이상");
				for (int i = 0; i < length; i++) {
					JSONObject group 	= (JSONObject) groups.get(i);
					JSONArray items 	= group.getJSONArray("items");

					int ilength 		= items.length();
					Log.i(tagName, "아이템 길이 : " + ilength);

					for (int j = 0; j < ilength; j++) {

						JSONObject item = (JSONObject) items.get(j);

						Venue venue 	= new Venue();

						venue.id 		= item.getString("id");
						venue.name		= item.getString("name");

						JSONObject location = item.getJSONObject("location");

						Location loc 	= new Location(LocationManager.GPS_PROVIDER);
						
						// 경도 위도 추출
						loc.setLatitude(Double.valueOf(location.getString("lat")));
						loc.setLongitude(Double.valueOf(location.getString("lng")));

						venue.location	= loc;
						// 주소가 null이 아닐 경우 추출
						if(location.isNull("address")){
							venue.transName = TranslateService.translate(venue.name);
						}else{
							venue.address	= location.getString("address");
							venue.transName = TranslateService.translate(venue.address + ".\n" + venue.name);							
						}

						venue.distance	= location.getInt("distance");
						venue.herenow	= item.getJSONObject("hereNow").getInt("count");
						venue.type		= group.getString("type");
						
						// categories array이가 null이 아닐 경우 아이콘 추출
						if(item.getJSONArray("categories").isNull(0)){
							// 널일 경우
							venue.iconUrl = "https://foursquare.com/img/categories/building/default.png";
						}else{
							// 아이콘 URL 추출
							JSONObject iconItem = item.getJSONArray("categories").getJSONObject(0);
							venue.iconUrl = iconItem.getString("icon");
						}

						
						venueList.add(venue);
					}
				}
			}
		} catch (Exception ex) {
			Log.i(tagName, "getNearby 메소드에서 Exception");
			throw ex;
		}
		Log.i(tagName, "리스트 리턴 전");
		return venueList;
	}
	
	// 팁 리스트 가져오기
	public ArrayList<Tips> getTips(String venueId){
		// 3. 포스퀘어 URL 에 ID을 파라미터로 넣고 요청
		ArrayList<Tips> fsTipList = new ArrayList<Tips>();
		
		try {

			URL tipsUrl = new URL(FS_API_URL + "/venues/" + venueId + "/tips?sort=recent" + "&oauth_token=" + fs.getAccessToken());

			Log.i(tagName, "유알엘 열기 : " + tipsUrl.toString());

			HttpURLConnection urlConnection;
			try {
				urlConnection = (HttpURLConnection) tipsUrl.openConnection();

				urlConnection.setRequestMethod("GET");
				urlConnection.setDoInput(true);
				urlConnection.setDoOutput(true);

				urlConnection.connect();

				Log.i(tagName, "컨넥션");
				String response		= streamToString(urlConnection.getInputStream());
				Log.i(tagName, response);
				JSONObject jsonObj 	= (JSONObject) new JSONTokener(response).nextValue();

				JSONArray items	= jsonObj.getJSONObject("response").getJSONObject("tips").getJSONArray("items");

				if(items.length() > 0){
					Log.i(tagName, "tip 목록 1 이상");
					for(int l = 0; l < items.length(); l++){
						JSONObject jsonObject = (JSONObject) items.get(l);
						
						Tips fsqTips = new Tips();
						// Tips 객체에 담기
						fsqTips.setId(jsonObject.getString("id"));
						fsqTips.setCreateAt(jsonObject.getInt("createdAt"));
						// 번역하여 담기
						String convertString = TranslateService.translate(jsonObject.getString("text"));
						fsqTips.setText(convertString);
						// 작성자 객체에서 이름 추출
						JSONObject userObject = jsonObject.getJSONObject("user");
						fsqTips.setUserFirstName(userObject.getString("firstName"));
						fsqTips.setUserLastName(userObject.getString("lastName"));
						
						// 리스트에 담기
						fsTipList.add(fsqTips);
					}
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.i(tagName, "item click examcple에서 exception");
				e.printStackTrace();
			}



		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 4. 출력
		return fsTipList;
	}
	
    public ArrayList<Photo> getPhotos(String venueId){
    	ArrayList<Photo> photoList = new ArrayList<Photo>();
		// 3. 포스퀘어 URL 에 ID을 파라미터로 넣고 요청
		try {
			URL photoUrl = new URL(FS_API_URL + "/venues/" + venueId + "/photos?group=venue" + "&oauth_token=" + fs.getAccessToken());

			Log.i(tagName, " 사진 유알엘 열기 : " + photoUrl.toString());

			HttpURLConnection urlConnection;
			try {
				urlConnection = (HttpURLConnection) photoUrl.openConnection();

				urlConnection.setRequestMethod("GET");
				urlConnection.setDoInput(true);
				urlConnection.setDoOutput(true);

				urlConnection.connect();

				Log.i(tagName, "사진 컨넥션");
				String response		= streamToString(urlConnection.getInputStream());
				JSONObject jsonObj 	= (JSONObject) new JSONTokener(response).nextValue();

				JSONArray items	= jsonObj.getJSONObject("response").getJSONObject("photos").getJSONArray("items");

				if(items.length() > 0){
					Log.i(tagName, "사진 목록 1 이상");
					for(int l = 0; l < items.length(); l++){
						JSONObject jsonObject = (JSONObject) items.get(l);
						
						Photo fsqPhoto = new Photo();
						fsqPhoto.setId(jsonObject.getString("id"));
						fsqPhoto.setCreatedAt(jsonObject.getInt("createdAt"));
						fsqPhoto.setUrl(jsonObject.getString("url"));
						
						// 사이즈별 배열 추출
						JSONArray sizes = jsonObject.getJSONObject("sizes").getJSONArray("items");
						
						// ThumbnailURL 추출 해서 담기
						JSONObject thumbnailObject = (JSONObject) sizes.get(2);
						fsqPhoto.setThumbnailUrl(thumbnailObject.getString("url"));
						
						photoList.add(fsqPhoto);
					}
					
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 4. 출력(일단 로그캣 확인)
    	return photoList;
    }
	
	public String streamToString(InputStream is) throws IOException {
		String str  = "";

		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;

			try {
				BufferedReader reader 	= new BufferedReader(new InputStreamReader(is));

				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}

				reader.close();
			} finally {
				is.close();
			}

			str = sb.toString();
		}

		return str;
	}
	
//	final class TraslateNameAddress implements Runnable{
//		private String beforeString;
//		private TextView view;
//		
//		public TraslateNameAddress(String beforeString, TextView view) {
//			super();
//			this.beforeString = beforeString;
//			this.view = view;
//		}
//
//		@Override
//		public void run() {
//			view.setText(TranslateService.translate(beforeString));
//		}
//		
//	}

}
